#!/usr/bin/env bash

# Standardized comments in English for clarity and consistency

# Change to home directory
cd "$HOME"

# Color definitions
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
CYAN="\033[36m"
RESET="\033[0m"

# Global variables
INSTALLED_PACKAGE=""
CHROMIUM_COMMAND=""
UNINSTALL_MODE=false
USE_MIRROR=true
PPA_FINGERPRINT="82BB6851C64F6880"
PPA_KEYSERVER="keyserver.ubuntu.com"
PPA_MIRRORS=("launchpad.proxy.ustclug.org" "ppa.launchpadcontent.net")
SELECTED_MIRROR=""

# Function to show help information
show_help() {
    echo -e "${GREEN}═══════════════════════════════════════════════════${RESET}"
    echo -e "${GREEN}  Ubuntu/Debian Chromium PPA Installer v3.1${RESET}"
    echo -e "${GREEN}═══════════════════════════════════════════════════${RESET}"
    echo ""
    echo -e "${YELLOW}Supported Systems:${RESET}"
    echo "  • Ubuntu 18.04+ (ARM64/armhf/amd64)"
    echo "  • Debian 10+ (ARM/x86)"
    echo "  • Ubuntu-based ARM distributions"
    echo ""
    echo -e "${YELLOW}Usage:${RESET}"
    echo "  sudo $0 [options]"
    echo ""
    echo -e "${YELLOW}Options:${RESET}"
    echo "  -h, --help         Show this help message"
    echo "  -u, --uninstall    Uninstall and reinstall"
    echo "  --no-mirror        Use official source (not recommended for users in China)"
    echo ""
    echo -e "${CYAN}Note: This script uses PPA for Chromium installation, optimized for ARM but works on x86 too.${RESET}"
    echo ""
}

# Logging functions (simplified to reduce redundant output)
log_info() { echo -e "${BLUE}[INFO]${RESET} $1"; }
log_success() { echo -e "${GREEN}[✓]${RESET} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${RESET} $1"; }
log_error() { echo -e "${RED}[✗]${RESET} $1"; exit 1; }
log_step() { echo -e "${CYAN}▶ $1${RESET}"; }

# Detect system architecture
detect_architecture() {
    ARCH=$(uname -m)
    case "$ARCH" in
        aarch64|arm64) FRAMEWORK="arm64" ;;
        armv7l|armhf) FRAMEWORK="armhf" ;;
        amd64|x86_64) 
            FRAMEWORK="amd64"
            log_warn "x86_64 detected. Official Chrome deb is recommended, but proceeding with PPA."
            ;;
        *) log_error "Unsupported architecture: $ARCH" ;;
    esac
    log_info "Architecture: $FRAMEWORK"
}

# Detect system version and codename
detect_system_version() {
    if [ ! -f /etc/os-release ]; then log_error "Cannot detect system version"; fi
    . /etc/os-release
    SYSTEM_ID="$ID"
    SYSTEM_VERSION="$VERSION_ID"
    SYSTEM_CODENAME="$VERSION_CODENAME"
    SYSTEM_NAME="$PRETTY_NAME"
    log_info "System: $SYSTEM_NAME (Codename: $SYSTEM_CODENAME)"
    case "$SYSTEM_ID" in
        ubuntu|debian|linuxmint|pop) log_success "Supported system" ;;
        *) 
            if command -v apt >/dev/null; then log_warn "Unknown Debian-based system, attempting install"
            else log_error "Only Debian/Ubuntu-based systems supported"; fi
            ;;
    esac
}

# Prepare system by updating and installing required tools
prepare_system() {
    log_step "Preparing system"
    apt update -y -qq || log_warn "apt update had warnings (ignoring)"
    TOOLS="wget curl gnupg ca-certificates apt-transport-https software-properties-common"
    for TOOL in $TOOLS; do
        if ! dpkg -l | grep -q "^ii  $TOOL "; then
            log_info "Installing $TOOL"
            apt install -y -qq "$TOOL"
        fi
    done
    log_success "System prepared"
}

# Test PPA mirror speeds and select the fastest
test_mirror_speed() {
    log_step "Testing PPA mirrors"
    FASTEST_MIRROR=""
    MIN_TIME=999999
    for MIRROR in "${PPA_MIRRORS[@]}"; do
        echo -ne "${CYAN}  Testing $MIRROR ... ${RESET}"
        START=$(date +%s%N)
        if timeout 3 curl -s -I "https://$MIRROR" >/dev/null; then
            END=$(date +%s%N)
            ELAPSED=$(( (END - START) / 1000000 ))
            echo -e "${GREEN}${ELAPSED}ms${RESET}"
            if [ "$ELAPSED" -lt "$MIN_TIME" ]; then MIN_TIME=$ELAPSED; FASTEST_MIRROR=$MIRROR; fi
        else echo -e "${RED}failed${RESET}"; fi
    done
    if [ -n "$FASTEST_MIRROR" ]; then
        SELECTED_MIRROR="$FASTEST_MIRROR"
        log_success "Fastest mirror: $SELECTED_MIRROR (${MIN_TIME}ms)"
    else
        SELECTED_MIRROR="ppa.launchpadcontent.net"
        log_warn "Using default official source"
    fi
}

# Add GPG key using multiple methods for reliability
add_gpg_key() {
    log_step "Adding GPG key"
    TEMP_KEYRING="/tmp/xtradeb-temp.gpg"
    # Method 1: Keyserver with gpg
    if gpg --no-default-keyring --keyring "$TEMP_KEYRING" --keyserver "hkp://$PPA_KEYSERVER:80" --recv-keys "$PPA_FINGERPRINT" 2>/dev/null; then
        gpg --no-default-keyring --keyring "$TEMP_KEYRING" --export "$PPA_FINGERPRINT" | apt-key add - 2>/dev/null
        rm -f "$TEMP_KEYRING" "$TEMP_KEYRING~"
        log_success "GPG key added (keyserver)"
        return 0
    fi
    # Method 2: apt-key direct
    if apt-key adv --keyserver "hkp://$PPA_KEYSERVER:80" --recv-keys "$PPA_FINGERPRINT" 2>/dev/null; then
        log_success "GPG key added (apt-key)"
        return 0
    fi
    # Method 3: Web fetch
    if wget -qO- "https://$PPA_KEYSERVER/pks/lookup?op=get&search=0x$PPA_FINGERPRINT" | apt-key add - 2>/dev/null; then
        log_success "GPG key added (web)"
        return 0
    fi
    # Method 4: Backup keyservers
    for SERVER in "keys.openpgp.org" "pgp.mit.edu"; do
        if apt-key adv --keyserver "hkp://$SERVER:80" --recv-keys "$PPA_FINGERPRINT" 2>/dev/null; then
            log_success "GPG key added ($SERVER)"
            return 0
        fi
    done
    log_error "All GPG key methods failed"
}

# Configure PPA source file
configure_ppa_source() {
    log_step "Configuring PPA source"
    LIST_FILE="/etc/apt/sources.list.d/xtradeb-apps.list"
    if [ "$USE_MIRROR" = true ] && [ "$SELECTED_MIRROR" != "ppa.launchpadcontent.net" ]; then
        PPA_URL="https://$SELECTED_MIRROR/xtradeb/apps/ubuntu"
        log_info "Using mirror: $SELECTED_MIRROR"
    else
        PPA_URL="https://ppa.launchpadcontent.net/xtradeb/apps/ubuntu"
        log_info "Using official source"
    fi
    echo "deb $PPA_URL $SYSTEM_CODENAME main" > "$LIST_FILE"
    log_success "PPA source configured"
}

# Add and verify PPA repository
add_ppa_repository() {
    add_gpg_key
    configure_ppa_source
    log_step "Updating package list"
    apt update 2>&1 | tee /tmp/apt_update.log
    if grep -q "NO_PUBKEY" /tmp/apt_update.log; then
        log_warn "Key issue detected, fixing..."
        grep "NO_PUBKEY" /tmp/apt_update.log | awk '{print $NF}' | sort -u | while read KEY; do
            log_info "Adding missing key: $KEY"
            apt-key adv --keyserver "hkp://$PPA_KEYSERVER:80" --recv-keys "$KEY" 2>/dev/null
        done
        apt update -y
    fi
    if apt-cache policy chromium | grep -q "xtradeb"; then log_success "PPA verified"; else log_error "PPA verification failed"; fi
}

# Check if Chromium is installed
check_chromium_installation() {
    if dpkg -l | grep -q "^ii  chromium "; then
        CHROMIUM_COMMAND="chromium"
        INSTALLED_PACKAGE="chromium"
        return 0
    fi
    return 1
}

# Create symlink for chromium-browser if needed
create_symlink() {
    SYMLINK_PATH="/usr/bin/chromium-browser"
    if command -v chromium >/dev/null && [ ! -e "$SYMLINK_PATH" ]; then
        ln -s "$(which chromium)" "$SYMLINK_PATH" 2>/dev/null
        log_success "Created symlink: chromium-browser"
    fi
}

# Uninstall Chromium and clean up
uninstall_chromium() {
    log_step "Uninstalling Chromium"
    rm -f /usr/bin/chromium-browser /usr/local/bin/chromium-browser 2>/dev/null
    PACKAGES="chromium chromium-browser chromium-codecs-ffmpeg"
    for PKG in $PACKAGES; do
        if dpkg -l | grep -q "^ii  $PKG "; then
            log_info "Uninstalling $PKG"
            apt remove --purge -y -qq "$PKG" 2>/dev/null
        fi
    done
    apt autoremove -y -qq 2>/dev/null
    rm -f /etc/apt/sources.list.d/xtradeb-apps.list
    apt update -y -qq 2>/dev/null
    log_success "Uninstall complete"
}

# Install Chromium via PPA
install_chromium_ppa() {
    log_step "Installing Chromium via PPA"
    if [ "$USE_MIRROR" = true ]; then test_mirror_speed; fi
    add_ppa_repository
    log_info "Installing Chromium..."
    if DEBIAN_FRONTEND=noninteractive apt install -y chromium; then
        INSTALLED_PACKAGE="chromium"
        log_success "Chromium installed"
        create_symlink
        return 0
    else log_error "Chromium installation failed"; fi
}

# Main installation logic
main_install() {
    if check_chromium_installation && [ "$UNINSTALL_MODE" = false ]; then
        log_success "Chromium already installed"
        log_info "Launch: chromium"
        create_symlink
        log_info "For reinstall: sudo $0 -u"
        return 0
    fi
    if [ "$UNINSTALL_MODE" = true ] && check_chromium_installation; then uninstall_chromium; fi
    install_chromium_ppa
}

# Verify installation and display summary
verify_installation() {
    echo -e "${GREEN}═══════════════════════════════════════════════════${RESET}"
    if check_chromium_installation; then
        log_success "Chromium verified"
        log_info "Package: $INSTALLED_PACKAGE"
        log_info "Launch: chromium or chromium-browser"
        VERSION=$(chromium --version 2>/dev/null || echo "Unknown")
        log_info "Version: $VERSION"
        echo -e "${CYAN}Usage:${RESET}"
        echo "  Launch: chromium"
        echo "  Uninstall: sudo apt remove chromium"
        if [ "$USE_MIRROR" = true ]; then log_info "Used mirror for faster install"; fi
    else log_error "Verification failed"; fi
    echo -e "${GREEN}═══════════════════════════════════════════════════${RESET}"
}

# Cleanup function
cleanup() { rm -f /tmp/apt_update.log /tmp/xtradeb-temp.gpg* 2>/dev/null; cd "$HOME"; }

# Main function
main() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help) show_help; exit 0 ;;
            -u|--uninstall) UNINSTALL_MODE=true ;;
            --no-mirror) USE_MIRROR=false ;;
            *) log_error "Unknown option: $1\nUse -h for help" ;;
        esac
        shift
    done
    if [[ $EUID -ne 0 ]]; then log_error "Run with sudo"; fi
    trap cleanup EXIT
    echo -e "${GREEN}═══════════════════════════════════════════════════${RESET}"
    echo -e "${GREEN}  Ubuntu/Debian Chromium PPA Installer${RESET}"
    echo -e "${GREEN}═══════════════════════════════════════════════════${RESET}"
    detect_architecture
    detect_system_version
    prepare_system
    main_install
    verify_installation
}

set -e
main "$@"